package com.musiklegal;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

public class NowPlaying extends Activity 
{
	Handler h= new Handler();
	Timer t;
	
	
	void init() throws IllegalArgumentException, IllegalStateException, IOException
	{
		
		
				
		
				 boolean p = true;
				if(!isSdPresent())
					{
						p=false;
						h.post(new Runnable(){

							public void run() {
								Toast.makeText(getApplicationContext(), Settings.sd, Toast.LENGTH_SHORT).show();
								finish();
							}});
						
						
					}
				 
				
				
						//startActivity(new Intent(getApplicationContext(),MusikLegal.class));
						//MusikLegal.log= PlaylistSender.loadLog();
					
						
					
				
			
		
	}
	
	public static boolean isSdPresent() {

		return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

		}
	
	public void onCreate(Bundle saved)
	{
		super.onCreate(saved);
		System.gc();
		
			
		Settings.jhentisubs=Language.jhentisubs;
		Settings.jmulaisubs=Language.jmulaisubs;
		Settings.jbangkrut=Language.jbangkrut;
		Settings.jteman=Language.jteman;
		Settings.joption=Language.joption;

		Settings.mulaisubs=Language.imulaisubs;
		Settings.warning = Language.iwarn;
		Settings.mulaisubs2=Language.imulaisubs2;
		Settings.hentisubs=Language.ihentisubs;
		Settings.bangkrut=Language.ibangkrut;
		Settings.gakonek=Language.igakonek;
		Settings.error=Language.ierror;
		Settings.thank=Language.ithanks;
		Settings.sd=Language.isd;
		Settings.sd=Language.isd;
		Settings.expp=Language.iexpp;
		Settings.expd=Language.iexpd;
		Settings.del=Language.idel;
		Settings.deal=Language.ideal;
		Settings.playlist=Language.iplaylist;
		Settings.info=Language.iinfo;
		Settings.nosos=Language.inosos;
		Settings.def=Language.idef;
		Settings.cari=Language.icari;
		Settings.nodef=Language.inodef;
		Settings.help=Language.ihelp;
	    
		Settings.yes=Language.iya;
		Settings.no=Language.itidak;
		Settings.topup=Language.itop;
		Settings.logout=Language.ilogout;
		
		

		setContentView(R.layout.nowplaying);
		
		
		TimerTask tt=new TimerTask(){

			@Override
			public void run() {
				try {
					init();
				} catch (IllegalArgumentException e) {
//					Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (IllegalStateException e) {
//					Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (IOException e) {
//					Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
				
						checkingData();
						if(checkLoginInfo())
						{
							
							
							h.post(new Runnable(){

								public void run() {
									startActivity(new Intent(getApplicationContext(), MainMenu.class));
								}});
				             
						}
						else
						{
							h.post(new Runnable(){

								public void run() {
									startActivity(new Intent(getApplicationContext(), MusikLegal.class));
								}});
						}
						h.post(new Runnable(){

							public void run() {
						finish();
							}});
						
					
				
			}};
			t = new Timer();
			t.schedule(tt, 100L);
	}
	
	void checkingData()
    {

        
        File main = new File(MusikLegal.mainFolder), 
        setting=new File(MusikLegal.settingFolder), 
        list = new File(MusikLegal.listD), 
        listPlay = new File(MusikLegal.playlist),
        albumart = new File(MusikLegal.albumArtFolder),
        cache = new File(MusikLegal.cacheFolder);
        MusikLegal.log = PlaylistSender.loadLog();
        MusikLegal.db = new DataHelper(this);
        MusikLegal.mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        
        String merchant = MusikLegal.mPreferences.getString("Catalogue", null);
        
        
        
        
        if(merchant!=null)
        {
        	String [] aa = merchant.split(";");
        	MainMenu.defaultMerchant = new MerchantEntity(aa[0],aa[1],aa[2],aa[3]);
        	
        }
        
        if(main.exists())
        {
        	if(!setting.exists())
        	{
        		setting.mkdir();
        		try {
					list.createNewFile();
					listPlay.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        	else
        	{
        		
        		if(list.exists())
        		{
        			
        			try {
        			
        				if(!listPlay.exists())
            				listPlay.createNewFile();
        				
						BufferedReader br = new BufferedReader(new FileReader(list));
						BufferedReader br1 = new BufferedReader(new FileReader(MusikLegal.playlist));
						
							buildList(br,br1);
        			}
						
					 catch (FileNotFoundException e) 
					{
						e.printStackTrace();
					}
					 catch (IOException e) 
					{
						e.printStackTrace();
					}
        		}
        		else
        		{
        			try 
        			{
        				list.createNewFile();
        				listPlay.createNewFile();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
        		}
        	}
        	
        	if(!albumart.exists())
        		albumart.mkdir();
        	
        	if(!cache.exists())
        		cache.mkdir();
        }
        else
        {
        	main.mkdir();
        	cache.mkdir();
        	setting.mkdir();
        	albumart.mkdir();
        	try 
        	{
				list.createNewFile();
			} catch (IOException e) 
			{	
				e.printStackTrace();
			}	
        }
    }
    
	private void buildList(BufferedReader download, BufferedReader play) throws IOException
    {
    	String song=null;
    	StringTokenizer token;
    	
    	SongD s;
    	song=download.readLine();
    	byte data []  = new byte[256];
    	while(song!=null){
    		
    		token = new StringTokenizer(song,SongD.delimiter);
    		
    		s=new SongD(token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken());
    		boolean added= MusikLegal.dataSet.add(s);
    		if(added)
    		{
    			MusikLegal.listDownload.add(0,s);
    		}
    		File f = new File(s.location);
    		
    		FileInputStream fis = new FileInputStream(f);
			fis.read(data);
			String k = new String(data);
			s.api = k.substring(177, 181).trim();
			fis.close();

    		song=download.readLine();
    		
    		
    	}
    	
    	
    	s = new SongD();
    	
    	song=play.readLine();
    	while(song!=null){
    		s.idRing = song;
    		if(MusikLegal.dataSet.contains(s) && !MusikLegal.myPlaylist.contains(s))
    		{
    			int index = MusikLegal.listDownload.indexOf(s);
    			
    			MusikLegal.myPlaylist.add(0,MusikLegal.listDownload.get(index));
    		}
    		song = play.readLine();
    	}
    	
    	song = play.readLine();
    	
    }
	
	private final boolean checkLoginInfo() {
		
        boolean username_set = MusikLegal.mPreferences.contains("UserName");
        boolean password_set = MusikLegal.mPreferences.contains("PassWord");
        
        if ( username_set || password_set ) {
        	
        	
    			/*try {
    				MusikLegal.checkSubscription(getApplicationContext());
    			} catch (ClientProtocolException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (ParserConfigurationException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (SAXException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}*/
            
        	
              return true;
        }
        return false;
  } 
	
}
